package com.joinway.framework.jpush.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;

import com.joinway.framework.jpush.bean.JPushResponse;

public abstract class JPushService {

	private final static Logger log = LoggerFactory.getLogger(JPushService.class);
	
	protected abstract PushResult doBroadcastMessage(String title, Map<String, String> extras, long seconds, boolean production) throws APIConnectionException, APIRequestException;
	
	protected abstract PushResult doMassMessage(String title, Map<String, String> extras, Collection<String> alias, long seconds, boolean production) throws APIConnectionException, APIRequestException;
	
	public abstract String getSupportMobileType();
	
	protected JPushClient client;
	
	/**
	 * 
	 * @param masterSecret
	 * @param appKey
	 */
	public JPushService(String masterSecret, String appKey){
		client = new JPushClient(masterSecret, appKey);
	}

	public JPushResponse broadcastMessage(String title, Map<String, String> extras, int liveDays, boolean production) {
		JPushResponse response = new JPushResponse();
		
		try{
			PushResult result = doBroadcastMessage(title, extras, convertDaysToSeconds(liveDays), production);
			log.debug("broadcast push result -> {}", result);
			
			response = createResponse(result);
		}catch(Exception e){
			log.error("error when broadcast {}", e);
			
			response = createResponse(e);
		}
		
		return response;		
	}
	
//	@Deprecated
//	public PushMessageResponseView massMessage(String title, Map<String, String> extras, String aliases, int liveDays, boolean production) {
//		List<String> ids = new ArrayList<>();
//		ids.add(aliases);
//		
//		return massMessage(title, extras, ids, liveDays, production);
//	}
	
	public JPushResponse massMessage(String title, Map<String, String> extras, Collection<String> alias, int liveDays, boolean production) {
		JPushResponse response = new JPushResponse();
		
		try{
			Collection<String> effectiveIds = new ArrayList<>();
			if(CollectionUtils.isNotEmpty(alias)){
				for(String id : alias){
					if(StringUtils.isNotEmpty(id)){
						effectiveIds.add(id);
					}
				}
			}
			
			if(CollectionUtils.isNotEmpty(effectiveIds)){
				PushResult result = doMassMessage(title, extras, effectiveIds, convertDaysToSeconds(liveDays), production);
				log.debug("mass push result -> {}", result);
				
				response = createResponse(result);
			}
		}catch(Exception e){
			log.error("error when mass broadcast {}", e);
			
			response = createResponse(e);
		}
		
		return response;
	}

//	public PushMessageResponseView massMessage(String title, Map<String, String> extras, Collection<String> alias, int liveDays, boolean production) {
//		PushMessageResponseView view = new PushMessageResponseView();
//		
//		try{
//			Collection<String> effectiveIds = new ArrayList<>();
//			if(CollectionUtils.isNotEmpty(alias)){
//				for(String id : alias){
//					if(StringUtils.isNotEmpty(id)){
//						effectiveIds.add(id);
//					}
//				}
//			}
//			
//			if(CollectionUtils.isNotEmpty(effectiveIds)){
//				PushResult result = doMassMessage(title, extras, effectiveIds, convertDaysToSeconds(liveDays), production);
//				log.debug("mass push result -> {}", result);
//				view = createResponseView(result);
//			}else{
//				log.warn("not effective id collection was found for title {}", title);
//				view.setCode(PushConstants.StatusCode.InvalidImId);
//				view.setError("not effective id collection was found for title [" + title + "]");
//			}
//		}catch(Exception e){
//			log.error("error when mass broadcast {}", e);
//			view = createResponseView(e);
//		}
//		
//		return view;
//	}
	
//	protected PushResult doBroadcastMessage(String title, Map<String, String> extras, long seconds, boolean production) throws APIConnectionException, APIRequestException{
//		PushPayload ppl = PushPayload.newBuilder()
//				.setPlatform(Platform.all())
//				.setAudience(Audience.all())
//				.setNotification(Notification.alert(title))
//				.setMessage(Message.newBuilder().setMsgContent("").addExtras(extras).build())
//				.build();
//		
//		ppl.resetOptionsTimeToLive(seconds);
//		ppl.resetOptionsApnsProduction(production);
//		
//		return client.sendPush(ppl);
//	}
//	
//	protected PushResult doMassMessage(String title, Map<String, String> extras, Collection<String> alias, long seconds, boolean production) throws APIConnectionException, APIRequestException{
//		PushPayload ppl = PushPayload.newBuilder()
//				.setPlatform(Platform.all())
//				.setAudience(Audience.alias(alias))
//				.setNotification(Notification.alert(title))
//				.setMessage(Message.newBuilder().setMsgContent("").addExtras(extras).build())
//				.build();
//		
//		ppl.resetOptionsTimeToLive(seconds);
//		ppl.resetOptionsApnsProduction(production);
//		
//		return client.sendPush(ppl);
//	}
	
	int convertDaysToSeconds(int liveDays){
		return liveDays * 24 * 60 * 60;
	}
	
	JPushResponse createResponse(PushResult result){
		JPushResponse response = new JPushResponse();
		
		response.setMessageId(result.msg_id);
		response.setSequenceNo(result.sendno);
		response.setSuccess(result.isResultOK());
		
		return response;
	}
	
	JPushResponse createResponse(Exception e){
		JPushResponse response = new JPushResponse();
		
		response.setError(e.getMessage());
		response.setSuccess(false);
		
		return response;
	}

//	PushMessageResponseView createResponseView(Exception e){
//		PushMessageResponseView view = new PushMessageResponseView();
//		
//		view.setCode(PushConstants.StatusCode.Fail);
//		view.setError(e.getMessage());
//		
//		return view;
//	}
}

